<template>
  <div class="cc-to-me-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>抄送我的</h2>
        <p>需要我知晓的审批流程信息</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="markAllAsRead">
          <el-icon><Check /></el-icon>
          全部标记已读
        </el-button>
        <el-button @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card unread">
        <div class="stat-icon">
          <el-icon><Message /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ unreadCount }}</div>
          <div class="stat-label">未读消息</div>
        </div>
      </div>
      <div class="stat-card total">
        <div class="stat-icon">
          <el-icon><Bell /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ totalCount }}</div>
          <div class="stat-label">总抄送数</div>
        </div>
      </div>
      <div class="stat-card today">
        <div class="stat-icon">
          <el-icon><Calendar /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ todayCount }}</div>
          <div class="stat-label">今日新增</div>
        </div>
      </div>
      <div class="stat-card urgent">
        <div class="stat-icon">
          <el-icon><Warning /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ urgentCount }}</div>
          <div class="stat-label">紧急事项</div>
        </div>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索抄送信息"
        style="width: 300px; margin-right: 15px;"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select v-model="statusFilter" placeholder="阅读状态" style="width: 120px; margin-right: 15px;">
        <el-option label="全部" value=""></el-option>
        <el-option label="未读" value="unread"></el-option>
        <el-option label="已读" value="read"></el-option>
      </el-select>
      <el-select v-model="typeFilter" placeholder="申请类型" style="width: 150px; margin-right: 15px;">
        <el-option label="全部" value=""></el-option>
        <el-option label="请假申请" value="请假申请"></el-option>
        <el-option label="加班申请" value="加班申请"></el-option>
        <el-option label="报销申请" value="报销申请"></el-option>
        <el-option label="调休申请" value="调休申请"></el-option>
        <el-option label="出差申请" value="出差申请"></el-option>
        <el-option label="采购申请" value="采购申请"></el-option>
      </el-select>
      <el-select v-model="urgencyFilter" placeholder="紧急程度" style="width: 120px; margin-right: 15px;">
        <el-option label="全部" value=""></el-option>
        <el-option label="普通" value="normal"></el-option>
        <el-option label="紧急" value="urgent"></el-option>
        <el-option label="非常紧急" value="very_urgent"></el-option>
      </el-select>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 240px;"
      ></el-date-picker>
    </div>

    <!-- 抄送列表 -->
    <div class="cc-table">
      <el-table :data="filteredCcItems" style="width: 100%" stripe>
        <el-table-column width="50">
          <template #default="{ row }">
            <el-icon v-if="!row.isRead" class="unread-indicator" color="#f56c6c"><CircleFilled /></el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="申请标题" width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span :class="{ 'unread-text': !row.isRead }">{{ row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="applicant" label="申请人" width="100"></el-table-column>
        <el-table-column prop="type" label="申请类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">{{ row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="流程状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="urgency" label="紧急程度" width="100">
          <template #default="{ row }">
            <el-tag :type="getUrgencyTagType(row.urgency)">{{ getUrgencyText(row.urgency) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentApprover" label="当前审批人" width="120"></el-table-column>
        <el-table-column prop="ccTime" label="抄送时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.ccTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetail(row)">查看</el-button>
            <el-button size="small" type="info" @click="viewProcess(row)">流程</el-button>
            <el-button 
              v-if="!row.isRead" 
              size="small" 
              type="success" 
              @click="markAsRead(row)"
            >
              标记已读
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalItems"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="抄送详情"
      width="700px"
    >
      <div v-if="currentItem" class="cc-detail">
        <!-- 申请信息 -->
        <div class="application-info">
          <h4>申请信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="申请标题">{{ currentItem.title }}</el-descriptions-item>
            <el-descriptions-item label="申请人">{{ currentItem.applicant }}</el-descriptions-item>
            <el-descriptions-item label="申请类型">
              <el-tag :type="getTypeTagType(currentItem.type)">{{ currentItem.type }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="紧急程度">
              <el-tag :type="getUrgencyTagType(currentItem.urgency)">{{ getUrgencyText(currentItem.urgency) }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="申请时间">{{ formatTime(currentItem.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="抄送时间">{{ formatTime(currentItem.ccTime) }}</el-descriptions-item>
            <el-descriptions-item label="申请原因" :span="2">{{ currentItem.reason }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 流程信息 -->
        <div class="process-info">
          <h4>流程信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="流程状态">
              <el-tag :type="getStatusTagType(currentItem.status)">{{ getStatusText(currentItem.status) }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="当前审批人">{{ currentItem.currentApprover }}</el-descriptions-item>
            <el-descriptions-item label="抄送原因" :span="2">{{ currentItem.ccReason }}</el-descriptions-item>
            <el-descriptions-item v-if="currentItem.nextApprover" label="下一审批人">{{ currentItem.nextApprover }}</el-descriptions-item>
            <el-descriptions-item v-if="currentItem.estimatedTime" label="预计完成时间">{{ formatTime(currentItem.estimatedTime) }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 附件信息 -->
        <div v-if="currentItem.attachments && currentItem.attachments.length" class="attachment-info">
          <h4>相关附件</h4>
          <div class="attachment-list">
            <div v-for="(file, index) in currentItem.attachments" :key="index" class="attachment-item">
              <el-icon><Document /></el-icon>
              <span class="attachment-name">{{ file.name }}</span>
              <el-button size="small" type="primary" link @click="downloadFile(file)">下载</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 流程图对话框 -->
    <el-dialog
      v-model="showProcessDialog"
      title="流程进度"
      width="800px"
    >
      <div class="process-timeline">
        <el-timeline>
          <el-timeline-item
            v-for="(step, index) in processSteps"
            :key="index"
            :timestamp="formatTime(step.time)"
            :type="getProcessStepType(step.status)"
            :hollow="step.status === 'pending'"
          >
            <div class="process-step">
              <div class="step-header">
                <span class="step-title">{{ step.title }}</span>
                <span class="step-user">{{ step.user }}</span>
              </div>
              <div class="step-content">{{ step.content }}</div>
              <div v-if="step.status === 'current'" class="step-current">
                <el-tag type="warning" size="small">当前节点</el-tag>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Download, Search, Check, Message, Bell, Calendar, Warning, 
  CircleFilled, Document 
} from '@element-plus/icons-vue'

// 响应式数据
const searchKeyword = ref('')
const statusFilter = ref('')
const typeFilter = ref('')
const urgencyFilter = ref('')
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const totalItems = ref(0)
const showDetailDialog = ref(false)
const showProcessDialog = ref(false)
const currentItem = ref(null)

// 抄送数据
const ccItems = ref([
  {
    id: 1,
    title: '张三的年假申请',
    applicant: '张三',
    type: '请假申请',
    status: 'approved',
    urgency: 'normal',
    currentApprover: '已完成',
    ccTime: new Date('2024-01-15 16:30:00'),
    createTime: new Date('2024-01-15 09:00:00'),
    isRead: false,
    reason: '年假休息，陪伴家人',
    ccReason: '请假申请已通过，请知悉',
    attachments: [
      { name: '请假申请表.pdf', url: '/files/leave-form.pdf' }
    ]
  },
  {
    id: 2,
    title: '李四的加班申请',
    applicant: '李四',
    type: '加班申请',
    status: 'pending',
    urgency: 'urgent',
    currentApprover: '王经理',
    ccTime: new Date('2024-01-15 14:20:00'),
    createTime: new Date('2024-01-15 10:30:00'),
    isRead: true,
    reason: '项目紧急，需要加班完成',
    ccReason: '加班申请需要您关注',
    nextApprover: '张总监',
    estimatedTime: new Date('2024-01-16 18:00:00')
  },
  {
    id: 3,
    title: '王五的报销申请',
    applicant: '王五',
    type: '报销申请',
    status: 'processing',
    urgency: 'normal',
    currentApprover: '财务部',
    ccTime: new Date('2024-01-15 11:45:00'),
    createTime: new Date('2024-01-15 08:15:00'),
    isRead: false,
    reason: '客户招待费用报销',
    ccReason: '报销申请进入财务审核阶段',
    attachments: [
      { name: '发票.jpg', url: '/files/invoice.jpg' },
      { name: '报销单.xlsx', url: '/files/expense.xlsx' }
    ]
  },
  {
    id: 4,
    title: '赵六的出差申请',
    applicant: '赵六',
    type: '出差申请',
    status: 'rejected',
    urgency: 'normal',
    currentApprover: '已拒绝',
    ccTime: new Date('2024-01-14 15:30:00'),
    createTime: new Date('2024-01-14 09:20:00'),
    isRead: true,
    reason: '客户现场技术支持',
    ccReason: '出差申请被拒绝，请知悉原因'
  },
  {
    id: 5,
    title: '孙七的采购申请',
    applicant: '孙七',
    type: '采购申请',
    status: 'pending',
    urgency: 'very_urgent',
    currentApprover: '采购部',
    ccTime: new Date('2024-01-15 17:00:00'),
    createTime: new Date('2024-01-15 16:45:00'),
    isRead: false,
    reason: '紧急采购办公设备',
    ccReason: '紧急采购申请，请关注进度',
    attachments: [
      { name: '采购清单.xlsx', url: '/files/purchase-list.xlsx' },
      { name: '供应商报价.pdf', url: '/files/quotation.pdf' }
    ]
  }
])

// 流程步骤数据
const processSteps = ref([
  {
    title: '发起申请',
    user: '张三',
    time: new Date('2024-01-15 09:00:00'),
    content: '提交年假申请，申请时间：2024年1月20日-1月25日',
    status: 'completed'
  },
  {
    title: '部门经理审批',
    user: '李经理',
    time: new Date('2024-01-15 14:30:00'),
    content: '同意年假申请，注意工作交接',
    status: 'completed'
  },
  {
    title: '人事部备案',
    user: '人事部',
    time: new Date('2024-01-15 16:20:00'),
    content: '年假申请已备案，假期余额已扣除',
    status: 'completed'
  },
  {
    title: '流程结束',
    user: '系统',
    time: new Date('2024-01-15 16:30:00'),
    content: '审批流程已完成，申请已通过',
    status: 'completed'
  }
])

// 计算属性
const filteredCcItems = computed(() => {
  let filtered = ccItems.value
  
  if (searchKeyword.value) {
    filtered = filtered.filter(item => 
      item.title.includes(searchKeyword.value) || 
      item.applicant.includes(searchKeyword.value) ||
      item.reason.includes(searchKeyword.value)
    )
  }
  
  if (statusFilter.value) {
    if (statusFilter.value === 'read') {
      filtered = filtered.filter(item => item.isRead)
    } else if (statusFilter.value === 'unread') {
      filtered = filtered.filter(item => !item.isRead)
    }
  }
  
  if (typeFilter.value) {
    filtered = filtered.filter(item => item.type === typeFilter.value)
  }
  
  if (urgencyFilter.value) {
    filtered = filtered.filter(item => item.urgency === urgencyFilter.value)
  }
  
  if (dateRange.value && dateRange.value.length === 2) {
    const [startDate, endDate] = dateRange.value
    filtered = filtered.filter(item => {
      const ccTime = new Date(item.ccTime)
      return ccTime >= startDate && ccTime <= endDate
    })
  }
  
  return filtered
})

const unreadCount = computed(() => {
  return ccItems.value.filter(item => !item.isRead).length
})

const totalCount = computed(() => {
  return ccItems.value.length
})

const todayCount = computed(() => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  const tomorrow = new Date(today)
  tomorrow.setDate(tomorrow.getDate() + 1)
  
  return ccItems.value.filter(item => {
    const ccTime = new Date(item.ccTime)
    return ccTime >= today && ccTime < tomorrow
  }).length
})

const urgentCount = computed(() => {
  return ccItems.value.filter(item => 
    item.urgency === 'urgent' || item.urgency === 'very_urgent'
  ).length
})

// 方法
const getTypeTagType = (type) => {
  const typeMap = {
    '请假申请': 'primary',
    '加班申请': 'success',
    '报销申请': 'warning',
    '调休申请': 'info',
    '出差申请': '',
    '采购申请': 'danger'
  }
  return typeMap[type] || 'default'
}

const getStatusTagType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'processing': 'primary',
    'approved': 'success',
    'rejected': 'danger'
  }
  return statusMap[status] || 'default'
}

const getStatusText = (status) => {
  const statusMap = {
    'pending': '待审批',
    'processing': '审批中',
    'approved': '已通过',
    'rejected': '已拒绝'
  }
  return statusMap[status] || status
}

const getUrgencyTagType = (urgency) => {
  const urgencyMap = {
    'normal': '',
    'urgent': 'warning',
    'very_urgent': 'danger'
  }
  return urgencyMap[urgency] || 'default'
}

const getUrgencyText = (urgency) => {
  const urgencyMap = {
    'normal': '普通',
    'urgent': '紧急',
    'very_urgent': '非常紧急'
  }
  return urgencyMap[urgency] || urgency
}

const getProcessStepType = (status) => {
  const typeMap = {
    'completed': 'success',
    'current': 'primary',
    'pending': 'info'
  }
  return typeMap[status] || 'info'
}

const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}

const markAllAsRead = () => {
  ccItems.value.forEach(item => {
    item.isRead = true
  })
  ElMessage.success('已全部标记为已读')
}

const markAsRead = (item) => {
  item.isRead = true
  ElMessage.success('已标记为已读')
}

const exportData = () => {
  ElMessage.success('数据导出功能开发中...')
}

const viewDetail = (item) => {
  currentItem.value = item
  showDetailDialog.value = true
  // 查看详情时自动标记为已读
  if (!item.isRead) {
    item.isRead = true
  }
}

const viewProcess = (item) => {
  currentItem.value = item
  showProcessDialog.value = true
  // 这里可以根据申请ID获取具体的流程步骤
}

const downloadFile = (file) => {
  ElMessage.success(`下载文件：${file.name}`)
  // 这里实现文件下载逻辑
}

const handleSizeChange = (val) => {
  pageSize.value = val
  // 重新加载数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 重新加载数据
}

// 生命周期
onMounted(() => {
  totalItems.value = ccItems.value.length
})
</script>

<style scoped>
.cc-to-me-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 24px;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-card.unread {
  border-left: 4px solid #f56c6c;
}

.stat-card.total {
  border-left: 4px solid #409eff;
}

.stat-card.today {
  border-left: 4px solid #67c23a;
}

.stat-card.urgent {
  border-left: 4px solid #e6a23c;
}

.stat-icon {
  font-size: 32px;
  margin-right: 15px;
  color: #666;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.filter-section {
  margin-bottom: 20px;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.cc-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.unread-indicator {
  font-size: 8px;
}

.unread-text {
  font-weight: 600;
  color: #333;
}

.pagination-section {
  text-align: right;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.cc-detail {
  padding: 10px 0;
}

.application-info,
.process-info,
.attachment-info {
  margin-bottom: 20px;
}

.application-info h4,
.process-info h4,
.attachment-info h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.process-info,
.attachment-info {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.attachment-item {
  display: flex;
  align-items: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  gap: 10px;
}

.attachment-name {
  flex: 1;
  color: #333;
}

.process-timeline {
  padding: 10px 0;
}

.process-step {
  margin-bottom: 10px;
}

.step-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.step-title {
  font-weight: 600;
  color: #333;
}

.step-user {
  color: #666;
  font-size: 14px;
}

.step-content {
  color: #666;
  line-height: 1.5;
  margin-bottom: 5px;
}

.step-current {
  margin-top: 5px;
}

:deep(.el-table) {
  border-radius: 0;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

:deep(.el-timeline-item__timestamp) {
  color: #909399;
  font-size: 12px;
}
</style>